package com.heritage.service;

import com.heritage.dto.response.HeritageResponse;
import com.heritage.entity.Heritage;
import com.heritage.entity.Like;
import com.heritage.entity.User;
import com.heritage.exception.ResourceNotFoundException;
import com.heritage.repository.HeritageRepository;
import com.heritage.repository.LikeRepository;
import com.heritage.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class HeritageService {

    @Autowired
    private HeritageRepository heritageRepository;

    @Autowired
    private LikeRepository likeRepository;

    @Autowired
    private UserRepository userRepository;

    public List<HeritageResponse> getAllHeritages() {
        List<Heritage> heritages = heritageRepository.findAllWithCategory();
        String currentUsername = getCurrentUsername();
        User currentUser = null;
        
        if (currentUsername != null) {
            currentUser = userRepository.findByUsername(currentUsername)
                    .orElse(null);
        }
        
        final User user = currentUser;
        
        return heritages.stream()
                .map(heritage -> convertToHeritageResponse(heritage, user))
                .collect(Collectors.toList());
    }

    public HeritageResponse getHeritageById(Long id) {
        Heritage heritage = heritageRepository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Heritage not found with id: " + id));
        
        String currentUsername = getCurrentUsername();
        User currentUser = null;
        
        if (currentUsername != null) {
            currentUser = userRepository.findByUsername(currentUsername)
                    .orElse(null);
        }
        
        return convertToHeritageResponse(heritage, currentUser);
    }

    @Transactional
    public boolean toggleLike(Long heritageId) {
        String username = getCurrentUsername();
        if (username == null) {
            throw new RuntimeException("User not authenticated");
        }
        
        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found"));
        
        Heritage heritage = heritageRepository.findById(heritageId)
                .orElseThrow(() -> new ResourceNotFoundException("Heritage not found with id: " + heritageId));
        
        boolean isLiked = likeRepository.existsByUserIdAndHeritageId(user.getId(), heritageId);
        
        if (isLiked) {
            // 取消点赞
            likeRepository.deleteByUserIdAndHeritageId(user.getId(), heritageId);
            return false;
        } else {
            // 添加点赞
            Like like = new Like();
            like.setUser(user);
            like.setHeritage(heritage);
            likeRepository.save(like);
            return true;
        }
    }

    private String getCurrentUsername() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof UserDetails) {
            return ((UserDetails) principal).getUsername();
        }
        return null;
    }

    private HeritageResponse convertToHeritageResponse(Heritage heritage, User currentUser) {
        HeritageResponse response = new HeritageResponse();
        response.setId(heritage.getId());
        response.setName(heritage.getName());
        response.setDescription(heritage.getDescription());
        response.setHistory(heritage.getHistory());
        response.setFeatures(heritage.getFeatures());
        response.setValue(heritage.getValue());
        response.setProtection(heritage.getProtection());
        response.setImage(heritage.getImage());
        response.setLevel(heritage.getLevel());
        
        if (heritage.getCategory() != null) {
            response.setCategoryId(heritage.getCategory().getId());
            response.setCategoryName(heritage.getCategory().getName());
        }
        
        // 获取点赞数
        int likesCount = likeRepository.countByHeritageId(heritage.getId());
        response.setLikes(likesCount);
        
        // 获取评论数
        response.setComments(heritage.getComments().size());
        
        // 检查当前用户是否点赞
        if (currentUser != null) {
            boolean isLiked = likeRepository.existsByUserIdAndHeritageId(currentUser.getId(), heritage.getId());
            response.setLiked(isLiked);
        } else {
            response.setLiked(false);
        }
        
        return response;
    }
}
